
import os.path
import vtk
import shutil
import matplotlib.pyplot as plt


def save_lung(pic, save_path='./lung3d'):
    if os.path.exists(save_path):
        shutil.rmtree(save_path)
    os.makedirs(save_path)
    for i in range(len(pic)):
        #     for i in range(1):
        plt.imsave(os.path.join(save_path, str(i) + ".png"), pic[i], cmap='gray')


def store_draw_3d(image):
    save_path = './lung3d'
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    save_lung(image, save_path=save_path)
    draw_3d(save_path)


def draw_3d(path, length=40):
    arender = vtk.vtkRenderer()
    arender.SetViewport(0, 0.0, 0.5, 1.0)
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(arender)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Reader = vtk.vtkMetaImageReader()
    # Reader.SetFileName("bbb.mhd")
    # Reader.Update()
    # 读取图片、面绘制
    Reader = vtk.vtkPNGReader()
    Reader.SetNumberOfScalarComponents(1)
    Reader.GetOutput().GetOrigin()
    Reader.SetDataByteOrderToLittleEndian()
    Reader.SetFileDimensionality(3)
    Reader.SetDataExtent(0, 512, 0, 512, 0, int(length))
    Reader.SetFilePrefix(path + "/")
    # Reader.SetFilePrefix("C:/Users/deng5/Desktop/2/48/")
    Reader.SetFilePattern("%s%d.png")
    Reader.SetDataSpacing(1, 1, 1)  # Volume Pixel
    Reader.Update()

    # 面绘制代码，详情见使用python-vtk完成面绘制文章
    skinExtractor = vtk.vtkContourFilter()
    skinExtractor.SetInputConnection(Reader.GetOutputPort())
    skinExtractor.SetValue(0, 1)
    skinExtractor.ComputeGradientsOn();
    skinExtractor.ComputeScalarsOn();
    smooth = vtk.vtkSmoothPolyDataFilter()
    smooth.SetInputConnection(skinExtractor.GetOutputPort())
    smooth.SetNumberOfIterations(100)

    skinNormals = vtk.vtkPolyDataNormals()
    skinNormals.SetInputConnection(smooth.GetOutputPort())
    skinNormals.SetFeatureAngle(50)

    skinStripper = vtk.vtkStripper()
    skinStripper.SetInputConnection(skinNormals.GetOutputPort())

    skinMapper = vtk.vtkPolyDataMapper()
    skinMapper.SetInputConnection(skinStripper.GetOutputPort())
    skinMapper.ScalarVisibilityOff()

    skin = vtk.vtkActor()

    skin.SetMapper(skinMapper)
    # 定义一个图像边界控件
    outlineData = vtk.vtkOutlineFilter()
    outlineData.SetInputConnection(Reader.GetOutputPort())

    mapOutline = vtk.vtkPolyDataMapper()
    mapOutline.SetInputConnection(outlineData.GetOutputPort())

    outline = vtk.vtkActor()
    outline.SetMapper(mapOutline)
    outline.GetProperty().SetColor(0, 0, 0)

    aCamera = vtk.vtkCamera()
    aCamera.SetViewUp(0, 0, -1)
    aCamera.SetPosition(0, 1, 0)
    aCamera.ComputeViewPlaneNormal()
    aCamera.Azimuth(30.0)
    aCamera.Elevation(30.0)
    aCamera.Dolly(1.5)
    arender.AddActor(outline)
    arender.AddActor(skin)
    # splineActor.GetProperty().SetLineWidth(5)
    # arender.AddActor(splineActor)
    # arender.AddActor(pointActor)
    arender.SetActiveCamera(aCamera)
    arender.ResetCamera()
    arender.SetBackground(.2, .3, .4)
    arender.ResetCameraClippingRange()

    renWin.SetSize(1000, 1000)
    style = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(style);
    # 定义切割器
    global cliper
    cliper = vtk.vtkClipPolyData()
    cliper.SetInputData(skinStripper.GetOutput())
    # 定义平面隐函数
    implicitPlaneWidget = vtk.vtkImplicitPlaneWidget()
    implicitPlaneWidget.SetInteractor(iren)
    implicitPlaneWidget.SetPlaceFactor(1.25)
    implicitPlaneWidget.SetInputData(skinStripper.GetOutput())
    implicitPlaneWidget.PlaceWidget()
    global coneSkinActor
    coneSkinActor = vtk.vtkActor()
    coneSkinActor.SetMapper(skinMapper)

    rRenderer = vtk.vtkRenderer()
    rRenderer.SetBackground(0.2, 0.3, 0.5)
    rRenderer.SetViewport(0.5, 0.0, 1.0, 1.0)

    coneSkinActor.RotateZ(90)
    rRenderer.AddActor(coneSkinActor)

    renWin.AddRenderer(rRenderer)
    # 关联CallBack函数
    implicitPlaneWidget.AddObserver("EndInteractionEvent", my_call_back)
    implicitPlaneWidget.On()

    renWin.Render()
    iren.Initialize()
    iren.Start()


# CallBack函数
def my_call_back(pWidget, ev):
    # 表示当pWidget控件改变时，触发函数
    if (pWidget):
        print(pWidget.GetClassName(), "Event Id:", ev)
        planeNew = vtk.vtkPlane()
        # 获得pWidget中的平面，将平面值赋值planeNew
        pWidget.GetPlane(planeNew)
        # cliper将裁剪器cliper的平面设置为planeNew
        cliper.SetClipFunction(planeNew)
        planeNew.GetNormal()
        cliper.Update()
        # 将裁减后的模型传递给另一个窗口
        clipedData = vtk.vtkPolyData()
        clipedData.DeepCopy(cliper.GetOutput())

        coneMapper = vtk.vtkPolyDataMapper()
        coneMapper.SetInputData(clipedData)
        coneMapper.ScalarVisibilityOff()
        coneSkinActor.SetMapper(coneMapper)
        print("Plane Normal = " + str(planeNew.GetNormal()))
        print("Plane Origin = " + str(planeNew.GetOrigin()))
